package com.otaku.consumer.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.otaku.common.ResultUtils.ResultModel;
import com.otaku.common.util.RestTemplateUtils;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class FanoutEmailConsumer {

    @RabbitHandler
    @RabbitListener(queues = "fanout_email_queue")
    public void process(Message message, @Headers Map<String,Object> headers, Channel channel) throws Exception {
        String messageId = message.getMessageProperties().getMessageId();
        System.out.println("UUID：" + messageId);
        String msg = new String(message.getBody(), "UTF-8");
        JSONObject object = JSONObject.parseObject(msg);
        String mail = object.get("email").toString();
        System.out.println("邮件消费者获取生产者消息msg:" + mail);
        //调用第三方接口转发
        String url = "http://127.0.0.1:8100/sendEmail?mail=" + mail;
        ResultModel result = RestTemplateUtils.sendMsg(url);
        String code = result.getCode();
        System.out.println("返回状态码：" + code);
        //手动应答ACK 在手动应答前，该消息不会被消息服务器删除
        long deliveryTag =(long) headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag,false);
    }
}
